//
// Created by Mac on 15-3-20.
// Copyright (c) 2015 Shishike. All rights reserved.
// @author   chenfei  @link 278338068@qq.com
//

#import "NSObject+Utility.h"


@implementation NSObject (Utility)

/**
* 主线程执行
*/
void JUSt_RUN_ON_UI_THREAD(dispatch_block_t block) {
    if ([NSThread isMainThread]) {
        block();
    } else {
        dispatch_sync(dispatch_get_main_queue(), block);
    }
}

/**
* 延迟在后台/主线程执行
*/
void JUST_DELAY_RUN_IN_UIMAINTHREAD_TIME(dispatch_block_t block, double time, BOOL mainQueue) {
    // 延期执行
    double delayInSeconds = time;
    // 创建延期的时间 2S，因为dispatch_time使用的时间是纳秒，尼玛，比毫秒还小，太夸张了！！！
    dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, (int64_t) (delayInSeconds * NSEC_PER_SEC));
    // 得到全局队列
    dispatch_queue_t concurrentQueue = mainQueue ? dispatch_get_main_queue() : dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    // 延期执行
    dispatch_after(delayInNanoSeconds, concurrentQueue, block);
}

/**
* 延迟0.25秒执行 主线程
*/
void JUST_DELAY_AFTER_RUN_IN_MAIN_THREAD(dispatch_block_t block) {
    // 延期执行
    double delayInSeconds = 0.25;
    // 创建延期的时间 2S，因为dispatch_time使用的时间是纳秒，尼玛，比毫秒还小，太夸张了！！！
    dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, (int64_t) (delayInSeconds * NSEC_PER_SEC));
    // 得到全局队列
    dispatch_queue_t concurrentQueue = dispatch_get_main_queue();
    // 延期执行
    dispatch_after(delayInNanoSeconds, concurrentQueue, block);
}

/**
* 运行在后台
*/

void Just_RUN_ON_BACKGROUD_THREAD(dispatch_block_t block) {
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block);
}

@end
